// Created by carolsail

import { ENUM_AUDIO_CLIP, ENUM_GAME_MODE, ENUM_UI_TYPE } from "../Enum";
import { StaticInstance } from "../StaticInstance";
import AudioManager from "../manager/AudioManager";
import DataManager from "../manager/DataManager";
import BaseLayer from "./Baselayer";
import { IRoom, IUser } from "../shared/common/types";
import ToastManager from "../manager/ToastManager";
import SdkManager from "../manager/SdkManager";
import PoolManager from "../manager/PoolManager";
import UIScrollControl from "../plugins/UIScrollControl";
import { wxAvatar } from "../Utils";
import ResourceManager from "../manager/ResourceManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class RoomLayer extends BaseLayer {

    panel: cc.Node = null
    btnStart: cc.Node = null
    btnStartOn: cc.Node = null
    btnStartOff: cc.Node = null
    btnShare: cc.Node = null
    btnClose: cc.Node = null
    title: cc.Node = null
    scrollNode: cc.Node = null
    scrollItem: cc.Node = null
    flyButtons: cc.Node = null
    aiCover: cc.Node = null
    // 房主
    owner: IUser = null
    flyIndex: number = 0

    onLoad() {
        this.panel = cc.find('style/panel', this.node)
        this.btnStart = cc.find('buttons/btn_start', this.panel)
        this.btnStartOn = cc.find('buttons/btn_start/on', this.panel)
        this.btnStartOff = cc.find('buttons/btn_start/off', this.panel)
        this.btnShare = cc.find('buttons/btn_share', this.panel)
        this.btnClose = cc.find('btn_close', this.panel)
        this.title = cc.find('title', this.panel)
        this.btnStartOn.on('click', this.onStartClick, this)
        this.btnShare.on('click', this.onShareClick, this)
        this.btnClose.on('click', this.onCloseClick, this)
        this.scrollNode = cc.find('scroll', this.panel)
        this.scrollItem = PoolManager.instance.getNode('RoomItem')
        this.flyButtons = cc.find('fly_buttons/buttons', this.panel)
        this.aiCover = cc.find('ai_cover', this.panel)
        this.aiCover.on('click', () => { this.onAiCoverClick() }, this)
        // DataManager.instance.wsClient.listenMsg('GameRefresh', ({ type, content }) => {
        //     if (type == 'msg_room_refresh') {
        //         this.rendor(content)
        //     } else if (type == 'msg_game_start') {
        //         this.onGameStartSync(content)
        //     } else if (type == 'msg_fly_index') {
        //         this.onFlyIndexSync(content)
        //     } else if (type == 'msg_ai_cover') {
        //         this.onAiCoverSync(content)
        //     }
        // })
    }

    onDestroy() {
        this.btnStartOn.off('click', this.onStartClick, this)
        this.btnShare.off('click', this.onShareClick, this)
        this.btnClose.off('click', this.onCloseClick, this)
        this.aiCover.off('click', this.onAiCoverClick, this)
        // DataManager.instance.wsClient.unlistenMsgAll('GameRefresh')
    }

    onEnable() {
        this.zoomIn(this.panel)
        this.rendorButton()
        this.rendor({ room: DataManager.instance.room })
    }

    onDisable() { }

    rendor({ room }) {
        if (!StaticInstance.uiManager.isActive(ENUM_UI_TYPE.ROOM)) return
        DataManager.instance.room = room
        const { id, players } = room
        // 房主
        this.owner = players[0]
        // 房间号
        this.title.getComponent(cc.Label).string = `房间(${id})`
        // 玩家
        let isScrollToTop = false
        this.scrollNode.getComponent(UIScrollControl).init(this.scrollItem, players.length, cc.size(500, 110), 0, (node: cc.Node, index: number) => {
            if (!isScrollToTop) {
                isScrollToTop = true
                this.scrollNode.getComponent(cc.ScrollView).scrollToTop()
            }
            const player = players[index]
            // 头像
            const avatar = node.getChildByName('avatar')
            const icon = avatar.getChildByName('icon')
            if (player.avatar) {
                wxAvatar(player.avatar).then((texture: any) => {
                    icon.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture)
                })
            } else {
                icon.getComponent(cc.Sprite).spriteFrame = ResourceManager.instance.getSprite('222')
            }
            // 名称
            const main = node.getChildByName('main')
            const nickname = main.getChildByName('nickname')
            nickname.getComponent(cc.Label).string = `${player.nickname}`
            // 说明
            const tips = main.getChildByName('tips')
            const icons = tips.getChildByName('icons')
            const label = tips.getChildByName('label')
            icons.children.forEach(icon => {
                icon.active = parseInt(icon.name) == index
            })
            label.getComponent(cc.Label).string = `${index + 1}P`
        }, (scroll: cc.ScrollView) => {
            scroll.scrollToTop()
        })
        // 开始按钮
        this.btnStart.active = DataManager.instance.user.openid == this.owner.openid
        this.btnStartOff.active = players.length <= 1
        this.btnStartOn.active = players.length > 1
        if (DataManager.instance.user.openid == this.owner.openid) {
            this.onFlyButtonCLick(DataManager.instance.canFlyIndex)
            this.onAiCoverClick(DataManager.instance.isAiCover)
        }
    }

    rendorButton(index: number = -1) {
        if (index >= 0) {
            this.flyButtons.children.forEach((button: cc.Node, key: number) => {
                const btnOn = button.getChildByName('on')
                const btnOff = button.getChildByName('off')
                btnOn.active = key == this.flyIndex
                btnOff.active = !(key == this.flyIndex)
            })
        } else {
            this.flyButtons.children.forEach((button: cc.Node, key: number) => {
                const btnOn = button.getChildByName('on')
                const btnOff = button.getChildByName('off')
                btnOn.active = key == this.flyIndex
                btnOff.active = !(key == this.flyIndex)
                if (!button.hasEventListener('click')) {
                    button.on('click', () => { this.onFlyButtonCLick(key) })
                }
            })
        }
    }

    onFlyButtonCLick(index: number) {
        if (this.owner.openid == DataManager.instance.user.openid) {
            const params = {
                type: 'msg_fly_index',
                room: DataManager.instance.room,
                content: {
                    canFlyIndex: index
                }
            }
            DataManager.instance.wsClient.callApi('GameSync', params)
        } else {
            ToastManager.instance.show('房主才具备权限', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }

    onAiCoverClick(isCover?: boolean) {
        if (isCover != undefined) {
            const params = {
                type: 'msg_ai_cover',
                room: DataManager.instance.room,
                content: {
                    isAiCover: isCover
                }
            }
            DataManager.instance.wsClient.callApi('GameSync', params)
            return
        }
        if (this.owner.openid == DataManager.instance.user.openid) {
            const params = {
                type: 'msg_ai_cover',
                room: DataManager.instance.room,
                content: {
                    isAiCover: !DataManager.instance.isAiCover
                }
            }
            DataManager.instance.wsClient.callApi('GameSync', params)
        } else {
            ToastManager.instance.show('房主才具备权限', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }

    async onCloseClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        await DataManager.instance.wsClient.callApi('RoomLeave', { player: DataManager.instance.user })
        DataManager.instance.room = null
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.ROOM, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.HALL)
    }

    onShareClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        if (typeof window['wx'] === 'undefined') {
            ToastManager.instance.show('仅支持小游戏平台', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
            return
        }
        const time = new Date().getTime()
        const roomId = DataManager.instance.room.id
        SdkManager.instance.activeShare({ title: '开黑走起~', query: `roomId=${roomId}&shareTime=${time}` })
    }

    onStartClick() {
        if (this.owner.openid == DataManager.instance.user.openid) {
            const room = DataManager.instance.room
            room.players.forEach(player => { player.status = 1 })
            room.status = 1
            const params = {
                type: 'msg_game_start',
                room: DataManager.instance.room,
                content: {
                    room
                }
            }
            DataManager.instance.wsClient.callApi('GameSync', params)
        } else {
            ToastManager.instance.show('房主才具备权限', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }

    onFlyIndexSync({ canFlyIndex }) {
        DataManager.instance.canFlyIndex = canFlyIndex
        this.flyIndex = canFlyIndex
        this.rendorButton(canFlyIndex)
    }

    onAiCoverSync({ isAiCover }) {
        DataManager.instance.isAiCover = isAiCover
        this.aiCover.getChildByName('on').active = DataManager.instance.isAiCover
        this.aiCover.getChildByName('off').active = !DataManager.instance.isAiCover
    }

    onGameStartSync({ room }) {
        if (!StaticInstance.uiManager.isActive(ENUM_UI_TYPE.ROOM)) return
        // 状态
        DataManager.instance.mode = ENUM_GAME_MODE.MULTIPLE
        DataManager.instance.room = room
        // 数据
        DataManager.instance.posData = [[], [], [], []]
        DataManager.instance.isAi = [true, true, true, true]
        if (DataManager.instance.isAiCover) {
            DataManager.instance.posData = [
                [-2, -2, -2, -2],
                [-2, -2, -2, -2],
                [-2, -2, -2, -2],
                [-2, -2, -2, -2]
            ]
        }
        DataManager.instance.room.players.forEach((_, index) => {
            DataManager.instance.posData[index] = [-2, -2, -2, -2]
            // DataManager.instance.posData[index] = [55, 55, 55, 49]
            DataManager.instance.isAi[index] = false
        })
        // 身份
        const role = DataManager.instance.room.players.findIndex(player => player.openid == DataManager.instance.user.openid)
        DataManager.instance.role = role
        // 回合
        DataManager.instance.round = 0
        // console.log(DataManager.instance.posData, DataManager.instance.isAi, `起飞:${DataManager.instance.canFlyIndex}`, `身份:${DataManager.instance.role}`)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.ROOM, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MAIN)
        StaticInstance.gameManager.onGameStart()
    }
}
